package com.github.nacosone.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置datasource到ioc容器里面
 *
 */
@Configuration
@MapperScan(basePackages = "com.github.nacosone.mapper")
public class DataSourceConfiguration {
	@Value("${spring.datasource.driver-class-name}")
	private String jdbcDriver;
	@Value("${spring.datasource.url}")
	private String jdbcUrl;
	@Value("${spring.datasource.username}")
	private String jdbcUsername;
	@Value("${spring.datasource.password}")
	private String jdbcPassword;

	/**
	 * 生成与spring-dao.xml对应的bean dataSource
	 *
	 * @return
	 * @throws PropertyVetoException
	 */
	@Bean(name = "dataSource")
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource dataSource() {
		return new DruidDataSource();
	}

	// 配置 Druid 监控管理后台的Servlet；
	@SuppressWarnings({ "unchecked", "rawtypes" })
	// 内置 Servlet 容器时没有web.xml文件，所以使用 Spring Boot 的注册 Servlet 方式
	@Bean
	public ServletRegistrationBean statViewServlet() {
		ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
		// 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet 的父类
		// com.alibaba.druid.support.http.ResourceServlet 中找到
		Map<String, String> initParams = new HashMap<>();

		initParams.put("loginUsername", "admin");
		initParams.put("loginPassword", "123456");
		initParams.put("allow", ""); // 默认就是允许所有访问

		// deny：Druid 后台拒绝谁访问，表示禁止此ip访问
		// initParams.put("deny","192.168.10.132");
		bean.setInitParameters(initParams);
		return bean;
	}

	// 2、配置一个web监控的filter
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Bean
	public FilterRegistrationBean webStatFilter() {
		FilterRegistrationBean bean = new FilterRegistrationBean();
		bean.setFilter(new WebStatFilter());

		Map<String, String> initParams = new HashMap<>();
		initParams.put("exclusions", "*.js,*.css,/druid/*");

		bean.setInitParameters(initParams);

		bean.setUrlPatterns(Arrays.asList("/*"));

		return bean;
	}

}
